import { Toast } from 'mint-ui'
import router from '../../router.js'
import MobileDetect from 'mobile-detect'
import EXIF from 'exif-js'
const host = window.localStorage.host// window.location.origin;
const apiHost = window.localStorage.apiHost

// eslint-disable-next-line no-extend-native
Array.prototype.remove = function (val) {
  const index = this.indexOf(val)
  if (index > -1) {
    this.splice(index, 1)
  }
}

function isiOS () {
  const md = new MobileDetect(window.navigator.userAgent)
  // console.log('mobile:', md);
  // alert(md.ua);
  // alert(md.os());
  if (md.os() === 'iOS') {
    // console.log('ios');
    return true
  } else {
    // console.log('android');
    return false
  }
}

// eslint-disable-next-line camelcase,no-unused-vars
function is_weixin () {
  var ua = navigator.userAgent.toLowerCase()
  // eslint-disable-next-line eqeqeq
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true
  } else {
    return false
  }
}

const isExits = (name) => {
  // 判断键值是否存在,localstorage.abc = '{}' 将返回 false
  if (typeof (window.localStorage.getItem(name)) === 'string') {
    try {
      const obj = JSON.parse(window.localStorage.getItem(name))
      if (typeof (obj) === 'object') {
        return Object.keys(JSON.parse(window.localStorage.getItem(name))).length > 0
      } else {
        return true
      }
    } catch (e) {
      return true
    }
  }
  return false
}

function GetQueryString (key) {
  var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')

  var result = window.location.search.substr(1).match(reg)

  return result ? decodeURIComponent(result[2]) : false
}

function funcUrlDel (name) {
  var loca = window.location

  var baseUrl = loca.origin + loca.pathname + '?'

  var query = loca.search.substr(1)

  if (query.indexOf(name) > -1) {
    var obj = {}

    var arr = query.split('&')

    for (var i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split('=')

      obj[arr[i][0]] = arr[i][1]
    }
    ;

    delete obj[name]

    var url = baseUrl + JSON.stringify(obj).replace(/["{}]/g, '').replace(/:/g, '=').replace(/,/g, '&')

    return url
  }
  ;
};

function getlinkSearch (key, reqStr) {
  var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')
  var result = reqStr.substr(1).match(reg)
  return result ? decodeURIComponent(result[2]) : false
}

function refreshUrl () {
  var url = ''
  var reqStr = ''
  if (GetQueryString('from')) { // from为微信二次分享自带参数
    url = funcUrlDel('from')
    var reqIndex = url.indexOf('?')
    reqStr = url.substr(reqIndex)// 截取去除from参数后的地址
    if (getlinkSearch('isappinstalled', reqStr)) { // isappinstalled为微信二次分享自带参数
      url = url.substr(0, url.indexOf('?'))// 截取去除isappinstalled参数后的地址
      window.location.href = url
    } else {
      window.location.href = url
    }
  }
}

// 获取url信息
function getInfoFromUrl (url) {
  var a = document.createElement('a')
  a.href = url
  return {
    source: url,
    protocol: a.protocol.replace(':', ''),
    host: a.hostname,
    port: a.port,
    query: a.search,
    params: (function () {
      var ret = {}
      var seg = a.search.replace(/^\?/, '').split('&')
      var len = seg.length
      var i = 0
      var s
      for (; i < len; i++) {
        if (!seg[i]) {
          continue
        }
        s = seg[i].split('=')
        ret[s[0]] = s[1]
      }
      return ret
    })(),
    // eslint-disable-next-line no-sparse-arrays
    file: (a.pathname.match(/([^/?#]+)$/i) || [, ''])[1],
    hash: a.hash.replace('#', ''),
    path: a.pathname.replace(/^([^/])/, '/$1'),
    // eslint-disable-next-line no-sparse-arrays
    relative: (a.href.match(/tps?:\/[^/]+(.+)/) || [, ''])[1],
    segments: a.pathname.replace(/^\//, '').split('/')
  }
}

export default {
  getInfoFromUrl: getInfoFromUrl,
  blobToDataURL: (blob, callback) => {
    var a = new FileReader()
    a.onload = function (e) {
      callback(e.target.result)
    }
    a.readAsDataURL(blob)
  },
  getFormDataByBlob: (blob, name) => {
    const formData = new FormData()
    // formData.append(name, blob, "file_" + Date.parse(new Date()) + ".png");
    formData.append(name, blob)
    return formData
  },
  getQueryString: (url, name) => {
    // console.log('url:',url);
    /* 定义正则，用于获取相应参数 */
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    /* 字符串截取，获取匹配参数值 */
    var index = url.indexOf('?')
    if (index === -1) {
      return null
    }
    var r = url.substr(index + 1).match(reg)
    /* 返回参数值 */
    if (r != null) {
      return decodeURI(r[2])
    } else {
      return null
    }
  },
  refreshUrl: refreshUrl,
  save: (name, obj) => {
    if (!name) return
    if (typeof (obj) !== 'string') {
      obj = JSON.stringify(obj)
    }
    window.localStorage.removeItem(name)
    window.localStorage.setItem(name, obj)
  },
  get: name => {
    if (!name) return
    return window.localStorage.getItem(name)
  },
  clear: (name) => {
    if (!name) return
    window.localStorage.removeItem(name)
  },
  clearAll: () => {
    window.localStorage.clear()
  },

  validateMobile: (mobile) => {
    // let telReg = /^1[3|4|5|7|8][0-9]{9}$/;
    // if (!telReg.test(mobile)) {
    //   Toast("请输入正确的手机号");
    //   return false;
    // } else {
    //   return true;
    // }
    if (mobile !== '') {
      return true
    } else {
      Toast('请输入手机号')
      return false
    }
  },
  formatNumToBool: (number) => {
    if (number === 1) {
      return true
    } else {
      return false
    }
  },
  formatBoolToNum: (bool) => {
    if (bool === true) {
      return 1
    } else {
      return 0
    }
  },
  host: host,
  apiHost: apiHost,
  backPrev: () => {
    // alert('history.length:'+history.length);
    if (history.length > 2) {
      router.go(-1)
    } else {
      router.push({ path: '/' })
    }
  },
  // 添加历史上一页
  addPrevPage: (url) => {
    if (window.history.length <= 2) {
      window.addEventListener('popstate', function (e) {
        window.location.href = url
      }, false)
    }
  },
  isReg: () => {
    if (isExits('init')) {
      const init = JSON.parse(window.localStorage.init)
      // alert('init.token:'+init.token);
      if (init.token) {
        return true
      } else {
        // eslint-disable-next-line eqeqeq
        return init.audit == 1
      }
    } else {
      return false
    }
  },
  // 用户身份状态
  userStatus: () => {
    // audit： 1，已审核，0，等待审核，-1，未注册
    if (isExits('init')) {
      const init = JSON.parse(window.localStorage.init)
      return init.audit
    }
  },
  // 生成包含1至maxNum的数组
  createNumArr: (maxNum) => {
    return Array.from({ length: maxNum }, (v, k) => k + 1)
  },
  isExits: isExits,
  getSignUrl: () => {
    // let url = window.location.href.split("#")[0];
    // if (isiOS()) {
    //   if(window.sessionStorage.url){
    //     url=window.sessionStorage.url.split("#")[0];
    //   }else{
    //     url=window.location.href.split("#")[0];
    //     window.sessionStorage.url = window.location.href;//ios 首次进入应用的url
    //   }
    // } else {
    //   url = window.location.href.split("#")[0];//android当前url
    // }
    let url = ''
    if (isiOS()) {
      if (window.sessionStorage.url) {
        url = window.sessionStorage.url
      } else {
        // 可能是分享出来的
        // alert("没找到url")
        // url=window.location.href.split("#")[0];
        // window.sessionStorage.url = window.location.href;//ios 首次进入应用的url
      }
    } else {
      url = window.location.href.split('#')[0]// android当前url
    }
    return url
  },
  isiOS: isiOS,
  fixIOSKeyboardBug: () => {
    /**
     * 处理iOS 微信客户端6.7.4 键盘收起页面未下移bug
     */
    ;(/iphone|ipod|ipad/i.test(navigator.appVersion)) && document.addEventListener('blur', (e) => {
      // 这里加了个类型判断，因为a等元素也会触发blur事件
      const top = document.body.scrollTop
      if (['input', 'textarea'].includes(e.target.localName) && document.body) {
        setTimeout(() => {
          document.body.scrollTop = top
        }, 20)
      }
    }, true)
  },
  getUrlBase64 (file) {
    var reader = new FileReader()
    reader.readAsDataURL(file)
    return new Promise((resolve, reject) => {
      let canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      let img = new Image()
      img.crossOrigin = 'Anonymous' // 开启img的“跨域”模式
      reader.onload = function () {
        img.src = this.result
        img.onload = function () {
          canvas.height = 300 / img.width * img.height
          canvas.width = 300
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height) // 参数可自定义
          const dataURL = canvas.toDataURL('image/jpeg', 0.75) // 获取Base64编码
          resolve(dataURL)
          canvas = null // 清除canvas元素
          img = null // 清除img元素
        }
      }
      img.onerror = function () {
        reject(new Error('Could not load image at ' + file))
      }
    })
  },
  rotatePhoto: async (file, callback) => {
    let Orientation
    // 这里的Exif是判断图片旋转的
    await EXIF.getData(file, function () {
      Orientation = EXIF.getTag(file, 'Orientation')
    })
    setTimeout(() => {
      if (!file || !window.FileReader) return
      if (/^image/.test(file.type)) {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onloadend = function () {
          const img = new Image()
          img.src = this.result
          img.onload = () => {
            const data = compress(img, Orientation)
            callback(data)
          }
        }
      }
    }, 500)

    const rotateImg = function (img, direction, canvas) {
      // 最小与最大旋转方向，图片旋转4次后回到原方向
      const minStep = 0
      const maxStep = 3
      if (img == null) return
      // img的高度和宽度不能在img元素隐藏后获取，否则会出错
      // 这里因为图片像素太大进行了一个3.5倍的缩放
      const height = img.height / 3.5
      const width = img.width / 3.5
      let step = 2
      if (direction === 'right') {
        step++
        // 旋转到原位置，即超过最大值
        step > maxStep && (step = minStep)
      } else {
        step--
        step < minStep && (step = maxStep)
      }
      // 旋转角度以弧度值为参数
      const degree = step * 90 * Math.PI / 180
      const ctx = canvas.getContext('2d')
      switch (step) {
        case 0:
          canvas.width = width
          canvas.height = height
          ctx.drawImage(img, 0, 0, width, height)
          break
        case 1:
          canvas.width = height
          canvas.height = width
          ctx.rotate(degree)
          ctx.drawImage(img, 0, -height, width, height)
          break
        case 2:
          canvas.width = width
          canvas.height = height
          ctx.rotate(degree)
          ctx.drawImage(img, -width, -height, width, height)
          break
        case 3:
          canvas.width = height
          canvas.height = width
          ctx.rotate(degree)
          ctx.drawImage(img, -width, 0, width, height)
          break
      }
    }
    const compress = function (img, Orientation) {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const width = img.width / 3.5
      const height = img.height / 3.5
      canvas.width = width
      canvas.height = height
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(img, 0, 0, width, height)
      // 处理ios手机旋转角度问题
      // 处理其安卓类手机图片旋转的问题
      // eslint-disable-next-line eqeqeq
      if (Orientation != '' && Orientation != 1) {
        switch (Orientation) {
          case 6:
            rotateImg(img, 'left', canvas)
            break
          case 8:
            rotateImg(img, 'right', canvas)
            break
          case 3:
            rotateImg(img, 'right', canvas)
            rotateImg(img, 'right', canvas)
            break
        }
      }
      return canvas.toDataURL('image/jpeg', 1)
    }
  }

// (file, callback) => {
//     let Orientation = null
//     console.log(file)
//     EXIF.getData(file, async function () {
//       console.log(file)
//       await EXIF.getAllTags(this)
//       Orientation = await EXIF.getTag(this, 'Orientation')
//       console.log(Orientation)
//       // const oReader = new FileReader()
//       // oReader.readAsDataURL(file)
//       // oReader.onload = function (e) {
//       //   console.log(e)
//       // }
//       // eslint-disable-next-line eqeqeq
//       if (Orientation != '' && Orientation != 1) {
//         // alert('旋转处理');
//         const canvas = document.createElement('canvas')
//         switch (Orientation) {
//           case 6: // 需要顺时针（向左）90度旋转
//             console.log('需要顺时针（向左）90度旋转')
//             rotateImg(this, 'left', canvas)
//             break
//           case 8: // 需要逆时针（向右）90度旋转
//             console.log('需要逆时针（向右）90度旋转')
//             rotateImg(this, 'right', canvas)
//             break
//           case 3: // 需要180度旋转
//             console.log('需要180度旋转')
//             rotateImg(this, 'right', canvas) // 转两次
//             rotateImg(this, 'right', canvas)
//             break
//         }
//         callback(canvas.toDataURL('image/png', 1))
//       } else {
//         callback()
//       }
//     })
//   }
}
